<template>
	<view class="container">
		<u-form :model="form" ref="uForm" label-width="200">
			<u-form-item label="姓名" prop="name" required>
				<u-input v-model="form.name" placeholder="请输入姓名" />
			</u-form-item>
			
			<u-form-item label="性别" prop="gender" required>
				<u-radio-group v-model="form.gender">
					<u-radio name="男">男</u-radio>
					<u-radio name="女">女</u-radio>
				</u-radio-group>
			</u-form-item>
			
			<u-form-item label="民族" prop="ethnicity" required>
				<u-input v-model="form.ethnicity" placeholder="请输入民族" />
			</u-form-item>
			
			<u-form-item label="一寸彩照" prop="photo" required>
				<view class="upload-section">
					<view class="upload-list">
						<view 
							v-for="(image, index) in uploadedImages.photo" 
							:key="index" 
							class="upload-item"
						>
							<image :src="image" mode="aspectFill" class="upload-image" />
							<view class="delete-btn" @click="deleteImage('photo', index)">×</view>
						</view>
					</view>
					<u-button 
						v-if="uploadedImages.photo.length < 1" 
						@click="chooseImage('photo')" 
						type="primary" 
						size="mini"
					>
						上传照片
					</u-button>
				</view>
			</u-form-item>
			
			<u-form-item label="户籍地址" prop="household_address" required>
				<u-input v-model="form.household_address" placeholder="请输入户籍地址" />
			</u-form-item>
			
			<u-form-item label="联系电话" prop="phone" required>
				<u-input v-model="form.phone" placeholder="请输入联系电话" />
			</u-form-item>
			
			<u-form-item label="身份证号码" prop="id_card" required>
				<u-input v-model="form.id_card" placeholder="请输入18位身份证号码" />
			</u-form-item>
			
			<u-form-item label="《就业创业证》号码" prop="employment_cert_number" required>
				<u-input v-model="form.employment_cert_number" placeholder="请输入就业创业证号码" />
			</u-form-item>
			
			<u-form-item label="补贴类别" prop="subsidy_category" required>
				<u-radio-group v-model="form.subsidy_category">
					<u-radio name="高校毕业生一次性创业补贴">高校毕业生一次性创业补贴</u-radio>
					<u-radio name="就业困难人员一次性创业补贴">就业困难人员一次性创业补贴</u-radio>
					<u-radio name="返乡创业人员一次性创业补贴">返乡创业人员一次性创业补贴</u-radio>
				</u-radio-group>
			</u-form-item>
			
			<u-form-item label="人员类别" prop="personnel_category" required>
				<u-checkbox-group v-model="form.personnel_category">
					<u-checkbox label="毕业学年在校大学生" name="毕业学年在校大学生"></u-checkbox>
					<u-checkbox label="毕业学年起五年内高校毕业生" name="毕业学年起五年内高校毕业生"></u-checkbox>
					<u-checkbox label="女性年满40周岁或者男性年满50周岁的失业人员" name="女性年满40周岁或者男性年满50周岁的失业人员"></u-checkbox>
					<u-checkbox label="连续失业一年以上人员" name="连续失业一年以上人员"></u-checkbox>
					<u-checkbox label="失地农民" name="失地农民"></u-checkbox>
					<u-checkbox label="城镇零就业家庭成员或享受城镇居民最低生活保障的人员" name="城镇零就业家庭成员或享受城镇居民最低生活保障的人员"></u-checkbox>
					<u-checkbox label="农村零转移就业贫困家庭成员" name="农村零转移就业贫困家庭成员"></u-checkbox>
					<u-checkbox label="毕业一年以上未就业的高校毕业生" name="毕业一年以上未就业的高校毕业生"></u-checkbox>
					<u-checkbox label="残疾人" name="残疾人"></u-checkbox>
					<u-checkbox label="各级社会福利机构供养的成年孤儿和社会成年孤儿" name="各级社会福利机构供养的成年孤儿和社会成年孤儿"></u-checkbox>
					<u-checkbox label="建档立卡贫困劳动力" name="建档立卡贫困劳动力"></u-checkbox>
					<u-checkbox label="返乡创业农民工" name="返乡创业农民工"></u-checkbox>
					<u-checkbox label="返乡创业大学生" name="返乡创业大学生"></u-checkbox>
					<u-checkbox label="返乡创业退役士兵" name="返乡创业退役士兵"></u-checkbox>
					<u-checkbox label="其他返乡人员" name="其他返乡人员"></u-checkbox>
				</u-checkbox-group>
			</u-form-item>
			
			<u-form-item label="创办项目名称" prop="project_name" required>
				<u-input v-model="form.project_name" placeholder="请输入创办项目名称" />
			</u-form-item>
			
			<u-form-item label="经营地址（或网址）" prop="business_address" required>
				<u-input v-model="form.business_address" placeholder="请输入经营地址或网址" />
			</u-form-item>
			
			<u-form-item label="工商注册时间" prop="registration_date" required>
				<u-input 
					v-model="form.registration_date" 
					placeholder="请选择工商注册时间" 
					readonly
					@click="showRegistrationCalendar = true"
				/>
			</u-form-item>
			
			<u-form-item label="统一社会信用代码" prop="credit_code" required>
				<u-input v-model="form.credit_code" placeholder="请输入统一社会信用代码" />
			</u-form-item>
			
			<u-form-item label="带动就业人数" prop="employment_count" required>
				<u-number-box v-model="form.employment_count" :min="0" :max="1000" />
			</u-form-item>
			
			<u-form-item label="开户行全称" prop="bank_name" required>
				<u-input v-model="form.bank_name" placeholder="请输入开户行全称" />
			</u-form-item>
			
			<u-form-item label="个人银行账号" prop="bank_account" required>
				<u-input v-model="form.bank_account" placeholder="请输入个人银行账号" />
			</u-form-item>
		</u-form>
		
		<!-- 工商注册时间日历 -->
		<u-calendar 
			v-model="showRegistrationCalendar" 
			mode="date" 
			@change="onRegistrationDateChange"
		></u-calendar>
		
		<!-- 底部固定提交按钮 -->
		<view class="submit-section">
			<u-button type="primary" @click="submitForm" :loading="submitting">提交申请</u-button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			form: {
				name: '',
				gender: '',
				ethnicity: '',
				photo: '',
				household_address: '',
				phone: '',
				id_card: '',
				employment_cert_number: '',
				subsidy_category: '',
				personnel_category: [],
				project_name: '',
				business_address: '',
				registration_date: '',
				credit_code: '',
				employment_count: 0,
				bank_name: '',
				bank_account: ''
			},
			rules: {
				name: [{
					required: true,
					message: '请输入姓名',
					trigger: ['blur', 'change']
				}],
				gender: [{
					required: true,
					message: '请选择性别',
					trigger: ['blur', 'change']
				}],
				ethnicity: [{
					required: true,
					message: '请输入民族',
					trigger: ['blur', 'change']
				}],
				household_address: [{
					required: true,
					message: '请输入户籍地址',
					trigger: ['blur', 'change']
				}],
				phone: [{
					required: true,
					message: '请输入联系电话',
					trigger: ['blur', 'change']
				}],
				id_card: [{
					required: true,
					message: '请输入身份证号码',
					trigger: ['blur', 'change']
				}],
				employment_cert_number: [{
					required: true,
					message: '请输入就业创业证号码',
					trigger: ['blur', 'change']
				}],
				subsidy_category: [{
					required: true,
					message: '请选择补贴类别',
					trigger: ['blur', 'change']
				}],
				personnel_category: [{
					required: true,
					message: '请选择人员类别',
					trigger: ['blur', 'change']
				}],
				project_name: [{
					required: true,
					message: '请输入创办项目名称',
					trigger: ['blur', 'change']
				}],
				business_address: [{
					required: true,
					message: '请输入经营地址',
					trigger: ['blur', 'change']
				}],
				registration_date: [{
					required: true,
					message: '请选择工商注册时间',
					trigger: ['blur', 'change']
				}],
				credit_code: [{
					required: true,
					message: '请输入统一社会信用代码',
					trigger: ['blur', 'change']
				}],
				employment_count: [{
					required: true,
					message: '请输入带动就业人数',
					trigger: ['blur', 'change']
				}],
				bank_name: [{
					required: true,
					message: '请输入开户行全称',
					trigger: ['blur', 'change']
				}],
				bank_account: [{
					required: true,
					message: '请输入个人银行账号',
					trigger: ['blur', 'change']
				}]
			},
			uploadedImages: {
				photo: []
			},
			showRegistrationCalendar: false,
			currentUploadType: '',
			submitting: false
		}
	},
	methods: {
		// 工商注册时间选择确认
		onRegistrationDateChange(e) {
			this.form.registration_date = e.result;
			this.showRegistrationCalendar = false;
		},
		
		// 选择图片
		chooseImage(type) {
			this.currentUploadType = type;
			if (this.uploadedImages[type].length >= 1) {
				uni.showToast({
					title: '只能上传1张照片',
					icon: 'none'
				});
				return;
			}

			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					this.uploadImages(res.tempFilePaths);
				},
				fail: (err) => {
					console.log('选择图片失败', err);
				}
			});
		},

		// 上传图片
		uploadImages(filePaths) {
			uni.showLoading({
				title: '上传中...'
			});

			const uploadPromises = filePaths.map(filePath => {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$api.uploadImage,
						filePath: filePath,
						name: 'file',
						success: (uploadFileRes) => {
							try {
								let data = JSON.parse(uploadFileRes.data);
								const url = data.data.url;
								resolve(url);
								uni.showToast({
									title: '上传成功',
									icon: 'success'
								});
							} catch (error) {
								reject(error);
							}
						},
						fail: (err) => {
							console.log('上传失败', err);
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
							reject(err);
						},
						complete: () => {
							uni.hideLoading();
						}
					});
				});
			});

			Promise.all(uploadPromises)
				.then(urls => {
					this.uploadedImages[this.currentUploadType] = [...this.uploadedImages[this.currentUploadType], ...urls];
					// 更新表单数据
					this.form.photo = this.uploadedImages.photo.join(',');
				})
				.catch(error => {
					console.log('批量上传失败', error);
				});
		},

		// 删除图片
		deleteImage(type, index) {
			this.uploadedImages[type].splice(index, 1);
			// 更新表单数据
			this.form.photo = this.uploadedImages.photo.join(',');
		},

		// 提交表单
		async submitForm() {
			try {
				// 表单验证
				const valid = await this.$refs.uForm.validate();
				if (!valid) {
					return;
				}
				
				// 检查必填图片
				if (!this.uploadedImages.photo || this.uploadedImages.photo.length === 0) {
					uni.showToast({
						title: '请上传一寸彩照',
						icon: 'none'
					});
					return;
				}
				
				// 显示加载提示
				uni.showLoading({
					title: '提交中...'
				});
				
				// 准备提交数据，将图片数组转换为逗号分隔的字符串
				const submitData = {
					...this.form,
					photo: this.uploadedImages.photo.join(',')
				};
				
				// 调用创建API
				await this.$api.startupSubsidyCreate(submitData);
				
				uni.hideLoading();
				
				uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					
					// 重置表单
					this.$refs.uForm.resetFields();
					this.uploadedImages = {
						photo: []
					};
					
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} catch (error) {
				console.log(error);
			}
		}
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 20rpx;
	padding-bottom: 120rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.upload-section {
	margin-top: 10rpx;
}

.upload-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.upload-item {
	position: relative;
	width: 120rpx;
	height: 120rpx;
}

.upload-image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.delete-btn {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	width: 40rpx;
	height: 40rpx;
	background-color: #ff4444;
	color: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
}

.submit-section {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 999;
}
</style>
